#include "Goal_MoveInGroup.h"
#include "Character.h"
#include "Goal_Types.h"

#include "Goal_FollowCharacter.h"
#include "Goal_ArriveAtDestination.h"
#include "Transformations.h"

#include "Message.h"
#include "General Utils.hpp"
#include "ExecutionLog.h"

Goal_MoveInGroup::Goal_MoveInGroup(Character* owner, Group* group):Goal_Composite<Character>(owner, goal_move_in_group),
																										m_pGroup(group)
{
	m_pLeader = m_pGroup->Leader();
	m_vDestination = m_pGroup->MoveGoal();
	m_vOffset = m_pGroup->NextFreeOffset();
}

	
void Goal_MoveInGroup::Activate()
{
	m_iStatus = active; 
	if(m_pLeader == m_pOwner)
		;//m_pOwner->TakePathToLocation(m_vDestination);

	else
		AddSubgoal(new Goal_FollowCharacter(m_pOwner, m_pLeader, m_vOffset));

	return;
}

int Goal_MoveInGroup::Process()
{
	ActivateIfInactive();

	if(m_pLeader->GroupID() != m_pOwner->GroupID())
	{
		Log->AddMessage("Following New Leader", GetFixedColor(255, 0, 255, 1));
		m_pGroup->Remove(m_pLeader);
		m_pGroup->Move(m_vDestination);
	}

	// If the leader has reached his destination. 
	if(m_pLeader->Pos().DistanceSq(m_vDestination) < 6400) // 80 units away
	{
		RemoveAllSubgoals(); // Stop following leader
		Vector2D Dest = PointToWorldSpace(m_vOffset, m_pLeader->Heading(), m_pLeader->Side(), m_pLeader->Pos());
		AddSubgoal(new Goal_ArriveAtDestination(m_pOwner, Dest));
	}

	m_iStatus = ProcessSubgoals();

	return m_iStatus;
}

void Goal_MoveInGroup::Terminate()
{
	RemoveAllSubgoals();
	m_pOwner->TurnSeparationOff();
	return;
}

bool Goal_MoveInGroup::HandleMessage(const Message& msg)
{
	return false;
}